package com.drought.rained.auth;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.drought.rained.R;
import com.drought.rained.base.BaseTitleActivity;
import com.drought.rained.bean.AuthInfoDataLJ;
import com.drought.rained.bean.DictionaryItemDataLJ;
import com.drought.rained.business.AuthRouterLJ;
import com.drought.rained.business.RouterMapLJ;
import com.drought.rained.cache.UserInfoLJ;
import com.drought.rained.common.ConstantLJ;
import com.drought.rained.dao.LocationDaoLJ;
import com.drought.rained.mvpview.DictionaryMvpViewLJ;
import com.drought.rained.mvpview.PersonalAuthMvpViewLJ;
import com.drought.rained.presenter.DictionaryPresenterLJ;
import com.drought.rained.presenter.PersonalAuthPresenterLJ;
import com.drought.rained.response.AuthInfoResponseLJ;
import com.drought.rained.response.BlankResponseLJ;
import com.drought.rained.utils.ToastUtilsLJ;
import com.drought.rained.view.LocationDialogLJ;
import com.drought.rained.view.MenuDialogLJ;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.DateTimePicker;

@Route(name = "个人信息认证", path = RouterMapLJ.PERSONAL_AUTH_PAGE)
public class PersonalAuthActivityLJ extends BaseTitleActivity implements PersonalAuthMvpViewLJ, DictionaryMvpViewLJ {

    @BindView(R.id.et_birthday)
    EditText etBirthday;
    @BindView(R.id.et_edu)
    EditText etEdu;
    @BindView(R.id.et_e_mail)
    EditText etEMail;
    @BindView(R.id.et_mother_name)
    EditText etMotherName;
    @BindView(R.id.et_family_num)
    EditText etFamilyNum;
    @BindView(R.id.et_child)
    EditText etChild;
    @BindView(R.id.et_province)
    EditText etProvince;
    @BindView(R.id.et_city)
    EditText etCity;
    @BindView(R.id.et_town)
    EditText etTown;
    @BindView(R.id.et_area)
    EditText etArea;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_area_code_big)
    EditText etAreaCodeBig;
    @BindView(R.id.et_area_code_small)
    EditText etAreaCodeSmall;
    @BindView(R.id.et_post)
    EditText etPost;
    @BindView(R.id.et_hourse_type)
    EditText etHourseType;
    @BindView(R.id.et_live_time)
    EditText etLiveTime;
    @BindView(R.id.tv_next_step)
    TextView tvNextStep;
    @BindView(R.id.et_rental_scope)
    EditText etRentalScope;
    @BindView(R.id.rl_rental_scope)
    RelativeLayout rlRentalScope;

    @Autowired(name = ConstantLJ.IS_BACK)
    boolean is_back;
    private PersonalAuthPresenterLJ personalAuthPresenter;
    private DictionaryPresenterLJ dictionaryPresenter;
    private DatePicker birthdayPicker;
    private DatePicker liveTimePicker;
    private ArrayList<DictionaryItemDataLJ> mXueliList;
    private ArrayList<DictionaryItemDataLJ> mFamilyList;
    private ArrayList<DictionaryItemDataLJ> mChildList;
    private ArrayList<DictionaryItemDataLJ> mRentalScope;
    private ArrayList<DictionaryItemDataLJ> mHourceowerList;
    private ArrayList<String> mProvinces;
    private ArrayList<String> mCitys;
    private ArrayList<String> mTowns;
    private ArrayList<String> mAreas;
    private final String DICTIONARY_TYPE_XUELI = "common_education";//教育
    private final String DICTIONARY_TYPE_NUMBER_OF_FAMILY_MEMBERS = "number_of_family_members"; // 家庭成员数量
    private final String DICTIONARY_TYPE_NUMBER_OF_CHILDREN = "number_of_children"; // 子女数量
    private final String DICTIONARY_TYPE_HOURCEOWER = "common_homeowner";
    private final String DICTIONARY_TYPE_RENTALSCOPECODE = "rental_scope";
    private MenuDialogLJ mMenuDialog;
    private LocationDialogLJ mLocationDialog;
    private LocationDaoLJ dao;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        dao = new LocationDaoLJ();
        etHourseType.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if ("租赁".equals(etHourseType.getText().toString()) || "Lease".equals(etHourseType.getText().toString()) || "KONTRAKAN/KOST".equals(etHourseType.getText().toString())) {
                    rlRentalScope.setVisibility(View.VISIBLE);
                } else {
                    rlRentalScope.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

    @Override
    protected void onUIReady() {
        ARouter.getInstance().inject(this);

        personalAuthPresenter = new PersonalAuthPresenterLJ(this);
        dictionaryPresenter = new DictionaryPresenterLJ(this);

        if (UserInfoLJ.isShowUserInformation())
            personalAuthPresenter.getAuthInfo();
        if (is_back) {
            tvNextStep.setText(R.string.save_change);
        }

        List<String> types = new ArrayList<>();
        types.add(DICTIONARY_TYPE_XUELI);
        types.add(DICTIONARY_TYPE_NUMBER_OF_FAMILY_MEMBERS);
        types.add(DICTIONARY_TYPE_NUMBER_OF_CHILDREN);
        types.add(DICTIONARY_TYPE_HOURCEOWER);
        types.add(DICTIONARY_TYPE_RENTALSCOPECODE);
        dictionaryPresenter.getDictionaryData(types);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_personal_auth_lj;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.personal_auth_page_name);
    }

    @Override
    public void onGetDataNext(AuthInfoResponseLJ response) {
        fillTextView(response.getData().getPersonageInfo());
    }

    @Override
    public void onGetDataNext(BlankResponseLJ response) {
        dismissLoadingView();
        if (response.getStatus() == ConstantLJ.HTTP_OK) {
            if (!is_back) {
                AuthRouterLJ.getInstance().jumpNextPager(this, RouterMapLJ.PERSONAL_AUTH_PAGE);
            } else {
                finish();
            }
        } else {
            ToastUtilsLJ.showShort(this, response.getMessage());
        }
    }

    private void fillTextView(AuthInfoDataLJ.PersonageInfoBean personageInfo) {
        etBirthday.setText(personageInfo.getBirthday());
        etEdu.setText(personageInfo.getEducationValue());
        etEdu.setTag(personageInfo.getEducation());
        etEMail.setText(personageInfo.getEmail());
        etMotherName.setText(personageInfo.getMotherName());
        etFamilyNum.setText(personageInfo.getFamilyNumValue());
        etFamilyNum.setTag(personageInfo.getFamilyNum());
        etChild.setText(personageInfo.getSonsNumValue());
        etChild.setTag(personageInfo.getSonsNum());
        etProvince.setText(personageInfo.getProvince());
        etCity.setText(personageInfo.getCity());
        etTown.setText(personageInfo.getTown());
        etArea.setText(personageInfo.getRegion());
        etAddress.setText(personageInfo.getAddress());
        etAreaCodeBig.setText(personageInfo.getBigRegionCode());
        etAreaCodeSmall.setText(personageInfo.getSmallRegionCode());
        etPost.setText(personageInfo.getZipCode());
        etHourseType.setText(personageInfo.getHomeownerValue());
        etHourseType.setTag(personageInfo.getHomeowner());
        etLiveTime.setText(personageInfo.getResidenceStartTime());
        etRentalScope.setText(personageInfo.getRentalScopeValue());
        etRentalScope.setTag(personageInfo.getRentalScopeCode());


    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }

    @OnClick({R.id.rl_birthday, R.id.et_birthday, R.id.rl_live_time, R.id.et_live_time})
    public void pickerTime(View view) {
        switch (view.getId()) {
            case R.id.rl_birthday:
            case R.id.et_birthday:
                pickerBirthDay();
                break;

            case R.id.rl_live_time:
            case R.id.et_live_time:
                pickerLiveTime();
                break;
        }

    }

    private void pickerLiveTime() {
        if (liveTimePicker == null) {
            Time time = new Time();

            time.setToNow();
            int year = time.year;
            int month = time.month + 1;
            int day = time.monthDay;
            liveTimePicker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY);
            liveTimePicker.setLabel(getStringResource(R.string.year_unit),
                    getStringResource(R.string.month_unit),
                    getStringResource(R.string.day_unit));
            liveTimePicker.setRangeStart(year - 30, 1, 1);//日期起点
            liveTimePicker.setSelectedItem(year, 1, 1); // 设置默认选中值
            liveTimePicker.setRangeEnd(year, month, day);//日期终点
            liveTimePicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                @Override
                public void onDatePicked(String year, String month, String day) {

                    etLiveTime.setText(year + "-" + month);
                }
            });
        }
        liveTimePicker.show();
    }

    private void pickerBirthDay() {
        if (birthdayPicker == null) {
            //24小时值
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String year = sdf.format(new Date());
            birthdayPicker = new DatePicker(this, DateTimePicker.YEAR_MONTH_DAY);
            birthdayPicker.setRangeStart(Integer.parseInt(year) - 50, 1, 1);//日期起点
            birthdayPicker.setSelectedItem(Integer.parseInt(year) - 25, 1, 1); // 设置默认选中值
            birthdayPicker.setRangeEnd(Integer.parseInt(year) - 15, 1, 1);//日期终点
            birthdayPicker.setLabel(getStringResource(R.string.year_unit),
                    getStringResource(R.string.month_unit),
                    getStringResource(R.string.day_unit));
            birthdayPicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
                @Override
                public void onDatePicked(String year, String month, String day) {

                    etBirthday.setText(year + "-" + month + "-" + day);
                }
            });
        }
        birthdayPicker.show();
    }

    @OnClick({R.id.rl_edu, R.id.et_edu, R.id.rl_family_num, R.id.et_family_num, R.id.rl_child, R.id.et_child, R.id.rl_province, R.id.et_province, R.id.rl_city, R.id.et_city, R.id.rl_town, R.id.et_town, R.id.rl_area, R.id.et_area, R.id.rl_hourse_type, R.id.et_hourse_type, R.id.rl_rental_scope, R.id.et_rental_scope, R.id.tv_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_edu:
            case R.id.et_edu:
                picker_edu();
                break;
            case R.id.rl_family_num:
            case R.id.et_family_num:
                pickerFamily();
                break;

            case R.id.rl_child:
            case R.id.et_child:
                pickerChild();
                break;
            case R.id.rl_province:
            case R.id.et_province:
                pickerProvince();
                break;
            case R.id.rl_city:
            case R.id.et_city:
                pickerCity();
                break;

            case R.id.rl_town:
            case R.id.et_town:
                pickerTown();
                break;

            case R.id.rl_area:
            case R.id.et_area:
                pickerArea();
                break;

            case R.id.rl_hourse_type:
            case R.id.et_hourse_type:
                pickerHourseType();
                break;

            case R.id.rl_rental_scope:
            case R.id.et_rental_scope:
                pickerRental_scope();
                break;
            case R.id.tv_next_step:
                commit();
                break;
                default:
                    break;
        }

    }

    private void pickerChild() {
        getMenuDialog().showDialog(etChild, mChildList);
    }

    private void picker_edu() {
        getMenuDialog().showDialog(etEdu, mXueliList);
    }

    private void pickerFamily() {
        getMenuDialog()
                .showDialog(etFamilyNum, mFamilyList);
    }

    private void pickerHourseType() {
        getMenuDialog().showDialog(etHourseType, mHourceowerList);

    }

    private void pickerRental_scope() {
        getMenuDialog().showDialog(etRentalScope, mRentalScope);
    }

    private void pickerProvince() {
        getLocationDialog().showDialog(etProvince, mProvinces);
    }

    private void pickerCity() {
        String province = etProvince.getText().toString();
        mCitys = dao.getCity(province);
        getLocationDialog().showDialog(etCity, mCitys);
    }


    private void pickerTown() {
        String province = etProvince.getText().toString();
        String city = etCity.getText().toString();
        mTowns = dao.getTown(province, city);
        getLocationDialog().showDialog(etTown, mTowns);
    }


    private void pickerArea() {
        String province = etProvince.getText().toString();
        String city = etCity.getText().toString();
        String town = etTown.getText().toString();
        mAreas = dao.getArea(province, city, town);
        getLocationDialog().showDialog(etArea, mAreas);
    }

    public MenuDialogLJ getMenuDialog() {
        if (mMenuDialog == null) {
            mMenuDialog = new MenuDialogLJ(this, R.style.dialog_bottom_full);
        }
        return mMenuDialog;
    }

    public LocationDialogLJ getLocationDialog() {
        if (mLocationDialog == null) {
            mLocationDialog = new LocationDialogLJ(this, R.style.dialog_bottom_full);
        }
        return mLocationDialog;
    }


    private void commit() {
        String birthDay = etBirthday.getText().toString().trim();
        String edu = (String) etEdu.getTag();
        String e_mail = etEMail.getText().toString().trim();
        String motherName = etMotherName.getText().toString().trim();
        String familyNum = (String) etFamilyNum.getTag();
        String childNum = (String) etChild.getTag();
        String province = etProvince.getText().toString().trim();
        String city = etCity.getText().toString().trim();
        String town = etTown.getText().toString().trim();
        String area = etArea.getText().toString().trim();
        String address = etAddress.getText().toString().trim();
        String bigCode = etAreaCodeBig.getText().toString().trim();
        String smallCode = etAreaCodeSmall.getText().toString().trim();
        String postNo = etPost.getText().toString().trim();
        String hourseType = (String) etHourseType.getTag();
        String liveTime = etLiveTime.getText().toString().trim();
        String rentalScopeCode = (String) etRentalScope.getTag();
        if (TextUtils.isEmpty(birthDay)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_birthday_hint);
            return;
        } else if (TextUtils.isEmpty(edu)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_edu_hint);
            return;
        } else if (TextUtils.isEmpty(e_mail)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_e_mail_hint);
            return;
        } else if (TextUtils.isEmpty(motherName)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_mother_name_hint);
            return;
        } else if (TextUtils.isEmpty(familyNum)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_family_num_hint);
            return;
        } else if (TextUtils.isEmpty(childNum)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_child_num_hint);
            return;
        } else if (TextUtils.isEmpty(province)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_province_hint);
            return;
        } else if (TextUtils.isEmpty(city)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_city_hint);
            return;
        } else if (TextUtils.isEmpty(town)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_town_hint);
            return;
        } else if (TextUtils.isEmpty(area)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_area_hint);
            return;
        } else if (TextUtils.isEmpty(address)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_address_hint);
            return;
        } else if (TextUtils.isEmpty(bigCode)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_code_big_hint);
            return;
        } else if (TextUtils.isEmpty(smallCode)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_code_small_hint);
            return;
        } else if (TextUtils.isEmpty(postNo)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_post_hint);
            return;
        } else if (TextUtils.isEmpty(hourseType)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_hourse_type_hint);
            return;
        } else if (TextUtils.isEmpty(liveTime)) {
            ToastUtilsLJ.showShort(this, R.string.personal_auth_live_time_hint);
            return;
        }
        if ("租赁".equals(etHourseType.getText().toString()) || "Lease".equals(etHourseType.getText().toString()) || "KONTRAKAN/KOST".equals(etHourseType.getText().toString())) {
            if (TextUtils.isEmpty(rentalScopeCode)) {
                ToastUtilsLJ.showShort(this, R.string.personal_auth_rental_scope_hint);
                return;
            }
        }


        Map<String, Object> map = new HashMap<>();
        map.put("birthday", birthDay);
        map.put("education", edu);
        map.put("email", e_mail);
        map.put("motherName", motherName);
        map.put("familyNum", familyNum);
        map.put("sonsNum", childNum);
        map.put("province", province);
        map.put("city", city);
        map.put("town", town);
        map.put("region", area);
        map.put("address", address);
        map.put("zipCode", postNo);
        map.put("bigRegionCode", bigCode);
        map.put("smallRegionCode", smallCode);
        map.put("residenceStartTime", liveTime);
        map.put("homeowner", hourseType);
        if (!TextUtils.isEmpty(rentalScopeCode)) {
            map.put("rentalScopeCode", rentalScopeCode);
        }

        personalAuthPresenter.saveAuthInfo(map);
        showLoadingView();
    }

    @Override
    public void onGetDataNext(ArrayList<ArrayList<DictionaryItemDataLJ>> responseWrapper) {
        if (responseWrapper.size() >= 4) {
            mXueliList = responseWrapper.get(0);
            mFamilyList = responseWrapper.get(1);
            mChildList = responseWrapper.get(2);
            mHourceowerList = responseWrapper.get(3);
            mRentalScope = responseWrapper.get(4);
        }
        mProvinces = dao.getProvince();
    }
}
